package com.du.ichat;

import android.annotation.SuppressLint;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.du.ichat.bean.AvatarBean;
import com.du.ichat.databinding.ActivityLoginBinding;
import com.du.ichat.utils.BaseActivity;
import com.du.ichat.utils.CheckSumBuilder;
import com.du.ichat.utils.SpUtils;
import com.du.ichat.utils.UserManager;
import com.du.ichat.utils.Utils;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.nos.NosService;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.constant.UserInfoFieldEnum;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;

public class LoginActivity extends BaseActivity {
    private ActivityLoginBinding binding;
    private boolean etUsernameHasWord,etPasswordHasWord;
    private FullDialog Dialogfull;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this , R.layout.activity_login);

        binding.usernameClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etUsername.setText("");
                view.setVisibility(View.GONE);
                setLoginBtnMode(false);
                etUsernameHasWord = false;
            }
        });
        binding.passwordClearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                binding.etPassword.setText("");
                view.setVisibility(View.GONE);
                setLoginBtnMode(false);
                etPasswordHasWord = false;
            }
        });
        binding.tvUsePhoneNum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toast("暂不支持手机号登录");
            }
        });

        binding.etUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                ChangeLineColor(binding.line1 , b);
                if(b){
                    if(!TextUtils.isEmpty(binding.etUsername.getText().toString())){
                        binding.usernameClearBtn.setVisibility(View.VISIBLE);
                    }
                }else{
                    binding.usernameClearBtn.setVisibility(View.GONE);
                }
            }
        });
        binding.etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    binding.usernameClearBtn.setVisibility(View.VISIBLE);
                    etUsernameHasWord = true;
                }else{
                    etUsernameHasWord = false;
                }

                if(etUsernameHasWord&&etPasswordHasWord){
                    setLoginBtnMode(true);
                }else{
                    setLoginBtnMode(false);
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.etPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                ChangeLineColor(binding.line2 , b);
                if(b){
                    if(!TextUtils.isEmpty(binding.etPassword.getText().toString())){
                        binding.passwordClearBtn.setVisibility(View.VISIBLE);
                    }
                }else{
                    binding.passwordClearBtn.setVisibility(View.GONE);
                }
            }
        });

        binding.etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if(!TextUtils.isEmpty(charSequence)){
                    binding.passwordClearBtn.setVisibility(View.VISIBLE);
                    etPasswordHasWord = true;
                }else{
                    etPasswordHasWord = false;
                }

                if(etUsernameHasWord&&etPasswordHasWord){
                    setLoginBtnMode(true);
                }else{
                    setLoginBtnMode(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        binding.loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialogfull.show(getSupportFragmentManager() , "loginloading");
                String username = binding.etUsername.getText().toString();
                String password = CheckSumBuilder.getMD5(binding.etPassword.getText().toString());
                LoginInfo info = new LoginInfo(username,password);
                NIMClient.getService(AuthService.class).login(info)
                        .setCallback(callback);
            }
        });

        binding.loginColseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LoginActivity.this.finish();
            }
        });

        Dialogfull = new FullDialog();

    }

    private void ChangeLineColor(View line , boolean focus){
        if(focus){
            line.setBackgroundColor(Color.parseColor("#1aad19"));
        }else{
            line.setBackgroundColor(Color.parseColor("#d8d8d8"));
        }
    }

    private RequestCallback<LoginInfo> callback = new RequestCallback<LoginInfo>() {
        @Override
        public void onSuccess(LoginInfo loginInfo) {
            Log.e("tag" , "login success , account : " + loginInfo.getAccount());
            SpUtils.putObject(LoginActivity.this , "logininfo" , loginInfo);

            getUserinfo(loginInfo);
        }

        @Override
        public void onFailed(int i) {
            Dialogfull.dismiss();
            switch (i){
                case 302:
                    toast("登录失败,账号密码不匹配！");
                    break;
            }

        }

        @Override
        public void onException(Throwable throwable) {
            toast("登录异常:" + throwable.getMessage());
            Dialogfull.dismiss();
        }
    };


    private void setLoginBtnMode(boolean canClick){
        binding.loginBtn.setClickable(canClick);
        if(canClick){
            binding.loginBtn.setBackgroundColor(Color.parseColor("#1aad19"));
            binding.loginBtn.setTextColor(Color.WHITE);
        }else{
            binding.loginBtn.setBackgroundColor(Color.parseColor("#9bd69b"));
            binding.loginBtn.setTextColor(Color.parseColor("#b9e2b9"));
        }
    }


    @SuppressLint("ValidFragment")
    public static class FullDialog extends DialogFragment{
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            this.setCancelable(false);
            return inflater.inflate(R.layout.dialog_login_loading , null , false);
        }
    }

    private void getUserinfo(final LoginInfo info){
        List<String> accounts = new ArrayList<>();
        accounts.add(info.getAccount());
        NIMClient.getService(UserService.class).fetchUserInfo(accounts).setCallback(new RequestCallback<List<NimUserInfo>>() {
            @Override
            public void onSuccess(List<NimUserInfo> nimUserInfos) {
                if(nimUserInfos.size()<=0){
                    Dialogfull.dismiss();
                    return;
                }
                NimUserInfo userinfo = nimUserInfos.get(0);
                SpUtils.putObject(LoginActivity.this , "userinfo" , userinfo);
                if(TextUtils.isEmpty(userinfo.getAvatar())){
                    uploadAvatar(userinfo.getAccount());
                }else{
                    SplashActiviy.finishSplashActivity();
                    startActivity(MainActivity.class);
                    LoginActivity.this.finish();
                }
//                downloadAvatarFile(info.getAccount());

            }

            @Override
            public void onFailed(int i) {
                log("getuserinfo failed : " + i);
            }

            @Override
            public void onException(Throwable throwable) {
                log("getuserinfo onException : ");
            }
        });
    }

    private void downloadAvatarFile(String account){
        BmobQuery<AvatarBean> query = new BmobQuery<>();
        query.addWhereEqualTo("accid" , account);
        query.findObjects(new FindListener<AvatarBean>() {
            @Override
            public void done(List<AvatarBean> list, BmobException e) {
                if(e == null){
                    if(list.size() != 0){
                        if(list.get(0).getFile() != null ){
                            if(Utils.avatarPath.exists()){
                                Utils.avatarPath.delete();
                                SpUtils.putString(LoginActivity.this , "bmobid" , list.get(0).getObjectId());
                            }
                            list.get(0).getFile().download(Utils.avatarPath ,new DownloadFileListener() {
                                @Override
                                public void done(String s, BmobException e) {
                                    Dialogfull.dismiss();
                                    if(e == null){
                                        SplashActiviy.finishSplashActivity();
                                        startActivity(MainActivity.class);
                                        LoginActivity.this.finish();
                                    }
                                }

                                @Override
                                public void onProgress(Integer integer, long l) {

                                }
                            });
                        }

                    }else{
                        Dialogfull.dismiss();
                    }

                }else{
                    Dialogfull.dismiss();
                }
            }
        });
    }


    private void uploadAvatar(final String accid){
        File localFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath(),
                CheckSumBuilder.getMD5(accid) + ".png");
        if(!localFile.exists()){
            SplashActiviy.finishSplashActivity();
            startActivity(MainActivity.class);
            LoginActivity.this.finish();
            return;
        }

        NIMClient.getService(NosService.class).upload(localFile , "image/png").setCallback(new RequestCallback<String>() {
            @Override
            public void onSuccess(String s) {
                Log.e("tag" , "11111111111 nosService success : " + s);
                updateUserAvatar(s);
            }

            @Override
            public void onFailed(int i) {
                Log.e("Tag" , "nosService faild : " + i);
//                fullDialog.dismiss();
            }

            @Override
            public void onException(Throwable throwable) {
//                fullDialog.dismiss();
            }
        });

    }

    private void updateUserAvatar(String avatarUrl){
        Map<UserInfoFieldEnum, Object> fields = new HashMap<>(1);
        fields.put(UserInfoFieldEnum.AVATAR, avatarUrl);
        NIMClient.getService(com.netease.nimlib.sdk.uinfo.UserService.class).updateUserInfo(fields).setCallback(new RequestCallback<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                List<String> accounts = new ArrayList<>();
                accounts.add(UserManager.getUserinfo(LoginActivity.this).getAccount());
                NIMClient.getService(com.netease.nimlib.sdk.uinfo.UserService.class).fetchUserInfo(accounts).setCallback(new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> nimUserInfos) {

                        if(nimUserInfos.size() >0 ){
                            SpUtils.putObject(LoginActivity.this ,"userinfo" , nimUserInfos.get(0));
                            toast("注册成功");
                            SplashActiviy.finishSplashActivity();
                            startActivity(MainActivity.class);
                            LoginActivity.this.finish();
                        }
                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
            }

            @Override
            public void onFailed(int i) {

            }

            @Override
            public void onException(Throwable throwable) {

            }
        });
    }

}
